<template>
  <div class="container" style="height: 100%;padding: 20px">

    <el-form v-loading="loading" ref="formUser" :rules="ruleUser" :model="user" style="width: 300px">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input type="password" v-model="user.oldPassword"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input type="password" v-model="user.password"></el-input>
      </el-form-item>
      <el-form-item label="重复新密码" prop="password_review">
        <el-input type="password" v-model="user.password_review"></el-input>
      </el-form-item>
      <el-button @click="handleChange">修改</el-button>
    </el-form>

  </div>
</template>

<script>

import { listMixin } from '@/mixin'
import { updatePassword } from '@/api/assessment'
import { logout, } from '@/api/common/common'

export default {
  name: 'Users',
  mixins: [listMixin],
  data() {
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.user.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      ruleUser: {
        oldPassword: [{ required: true, message: '请输入 原密码' }],
        password: [{ required: true, message: '请输入 新密码' }],
        password_review: [{ required: true, message: '请输入 重复新密码' }, { validator: validatePass2, trigger: 'blur' }],
      },
      user: {
        oldPassword: '',
        password: '',
        password_review: '',
      }
    }
  },
  methods: {
    handleChange() {
      this.$refs['formUser'].validate((valid) => {
        if (!valid) {return}

        this.loading = true
        updatePassword(this.user).then(res => {
          if (res.code !== 10000) {
            this.loading = false
            return
          }
          this.$message.success(res.msg)

          logout()
          this.$router.push({ path: '/login' })
          this.$store.commit('cancel')
          this.loading = false
        })
      })

    }
  }
}
</script>